package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dbutil.DBUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	@SuppressWarnings("unused")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setContentType("text/html;charset=utf-8");
  		request.setCharacterEncoding("UTF-8");
        HttpSession httpSession=request.getSession();
		String name = request.getParameter("Uname");
		String password = request.getParameter("password");
		JSONArray jsonarray = new JSONArray();
		JSONObject jsonobj = new JSONObject();
		DBUtil db=new DBUtil();
		Connection conn = db.getConn();
		try {
			String sql;
			String pass="";
			sql="select * from User where Uname='"+name+"'";
			ResultSet rs = db.getResult(sql);
			if(rs.next()) {
				pass = rs.getString("password");
				if(password.equals(pass)) {
					if(rs.getBoolean("root")) {
						Cookie cookie = new Cookie("root","true");
				        System.out.println("1"+cookie);
				        response.addCookie(cookie);
					}else {
						Cookie cookie = new Cookie("root","false");
				        System.out.println("1"+cookie);
				        response.addCookie(cookie);
					}
					jsonobj.put("adreess","index");
					jsonarray.put(jsonobj);
					response.getWriter().println(jsonarray);
			        response.sendRedirect("index.jsp");
				}else {
					httpSession.setAttribute("error1","密码错误");
					
					jsonobj.put("adreess","login");
					jsonarray.put(jsonobj);
					response.getWriter().println(jsonarray);
					response.sendRedirect("./PAGES/login.jsp");
					
					httpSession.setMaxInactiveInterval(10);
				}
			}else {
				httpSession.setAttribute("error1","用户不存在");
				jsonobj.put("adreess","login");
				jsonarray.put(jsonobj);
				response.getWriter().println(jsonarray);
				response.sendRedirect("./PAGES/login.jsp");
				httpSession.setMaxInactiveInterval(10);
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(db!=null)
				db.release();
		} 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
